package org.zoomdev.zoom.ioc.impl.factories;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.zoomdev.zoom.common.caster.ValueCaster;
import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.common.utils.Classes;
import org.zoomdev.zoom.common.utils.PatternUtils;
import org.zoomdev.zoom.ioc.MethodParameterNamesGetter;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 解决method的参数
 * <p>
 * 例如    void add(int a,int b);    {$1}  {$2}  表示 a 与 b的值，  {$a} {$b} 也表示a与b的值
 */
public final class ParameterAdapterFactory {

    private static final Pattern PARAM_PATTERN = Pattern.compile("\\{(\\$[0-9]+|[a-zA-Z0-9$]+)([\\.[a-zA-Z0-9$]+]*)\\}");


    public static String[] getValues(ParameterAdapter[] adapters, Object[] args) {
        String[] values = new String[adapters.length];
        for (int i = 0; i < values.length; ++i) {
            values[i] = adapters[i].getValue(args);
        }
        return values;
    }

    public static ParameterAdapterResponse parse(String key, Class<?> targetClass,
                                                 Method method,
                                                 MethodParameterNamesGetter getter) {
        Class<?>[] types = method.getParameterTypes();
        String[] names = getter.getParameterNames(targetClass, method);
        List<ParameterAdapter> adapters = new ArrayList<>();

        StringBuilder sb = new StringBuilder();
        PatternUtils.visit(key, PARAM_PATTERN, new PatternUtils.PatternVisitor() {
            @Override
            public void onGetPattern(Matcher matcher) {
                String name = matcher.group(1);
                String field = matcher.group(2);
                if (!StringUtils.isEmpty(field)) {
                    field = field.substring(1);
                }
                int index;
                if (name.startsWith("$")) {
                    String num = name.substring(1);
                    int n = Integer.parseInt(num);
                    if (n <= 0) {
                        throw new ZoomException("参数" + key + "不正确，数字下标从1开始:" + name + " " + method);
                    }
                    if (n > types.length) {
                        throw new ZoomException("参数" + key + "不正确，数字下标最大为:" + types.length + " " + name + " " + method);
                    }
                    index = n - 1;
                } else {
                    index = ArrayUtils.indexOf(names, name);
                    if (index < 0) {
                        //index = 0;
                        throw new ZoomException("参数" + key + "不正确，找不到参数，名称:" + name + " " + method);
                    }
                }
                ValueCaster caster = ParameterAdapterFactory.create(types[index], field, name);
                adapters.add(new ParameterAdapterFactory.ParameterAdapter(index, caster));

                sb.append("%s");
            }

            @Override
            public void onGetRest(int start, String rest) {
                if (rest.contains("{") || rest.contains("}")) {
                    throw new ZoomException("参数" + key + "格式不正确:" + rest + " " + method);
                }
                sb.append(rest);
            }
        });

        return new ParameterAdapterResponse(adapters.toArray(new ParameterAdapter[adapters.size()]), sb.toString());
    }


    static ValueCaster getAdapter(Class<?> type, String fieldName) {
        Field field = Classes.getField(type, fieldName);
        if (field != null) {
            field.setAccessible(true);
            return new FieldParameterAdapter(field);
        }

        Method method = Classes.getGetter(type, fieldName);
        if (method != null) {
            return new GetterParameterAdapter(method);
        }
        throw new ZoomException(type + " 找不到字段" + fieldName);
    }

    static ValueCaster getWrapAdapter(Class<?> type, String[] names, int index) {
        if (index == names.length - 1) {
            return getAdapter(type, names[index]);
        }
        String fieldName = names[index];
        Field field = Classes.getField(type, fieldName);
        Class<?> fType = field.getType();
        if (field != null) {
            field.setAccessible(true);
            return new FieldParameterWrapAdapter(field, getWrapAdapter(fType, names, index + 1));
        }

        Method method = Classes.getGetter(type, fieldName);
        if (method != null) {
            return new GetterParameterWrapAdapter(method, getWrapAdapter(type, names, index + 1));
        }
        throw new ZoomException(type + " 找不到字段" + fieldName);
    }

    static ValueCaster create(Class<?> type, String fieldName, String name) {
        if (Classes.isSimple(type)) {
            return StringParameterAdapter.ADAPTER;
        } else if (Map.class.isAssignableFrom(type)) {
            if (StringUtils.isEmpty(fieldName)) {
                throw new ZoomException("Map类型的参数必须配置字段名称:" + name);
            }
            return new MapParameterAdapter(fieldName);
        } else {
            if (fieldName.contains(".")) {
                String[] parts = fieldName.split("\\.");
                return getWrapAdapter(type, parts, 0);
            } else {
                return getAdapter(type, fieldName);
            }

        }
    }

    public static class ParameterAdapterResponse {
        public final ParameterAdapter[] adapters;
        public final String format;

        ParameterAdapterResponse(ParameterAdapter[] adapters, String format) {
            this.adapters = adapters;
            this.format = format;
        }
    }

    public static class ParameterAdapter {

        private final int index;

        private final ValueCaster caster;

        public ParameterAdapter(int index, ValueCaster caster) {
            this.index = index;
            this.caster = caster;
        }


        public String getValue(Object[] args) {
            return String.valueOf(caster.to(args[index]));
        }
    }

    public static class StringParameterAdapter implements ValueCaster {

        public static final StringParameterAdapter ADAPTER = new StringParameterAdapter();

        @Override
        public Object to(Object value) {
            return value;
        }
    }

    public static class MapParameterAdapter implements ValueCaster {


        private final String name;

        public MapParameterAdapter(String name) {
            this.name = name;
        }


        @Override
        public Object to(Object value) {
            return ((Map) value).get(name);
        }
    }


    static class GetterParameterWrapAdapter implements ValueCaster {


        private final Method getter;
        private final ValueCaster valueCaster;

        public GetterParameterWrapAdapter(Method getter, ValueCaster valueCaster) {
            this.getter = getter;
            this.valueCaster = valueCaster;
        }


        @Override
        public Object to(Object value) {
            try {

                Object value1 = getter.invoke(value);
                return valueCaster.to(value1);
            } catch (IllegalAccessException e) {
                throw new ZoomException(e);
            } catch (InvocationTargetException e) {
                throw new ZoomException(e);
            }
        }
    }

    static class GetterParameterAdapter implements ValueCaster {


        private final Method getter;

        public GetterParameterAdapter(Method getter) {
            this.getter = getter;
        }


        @Override
        public Object to(Object value) {
            try {
                return getter.invoke(value);
            } catch (IllegalAccessException e) {
                throw new ZoomException(e);
            } catch (InvocationTargetException e) {
                throw new ZoomException(e);
            }
        }
    }

    static class FieldParameterWrapAdapter implements ValueCaster {


        private final Field field;
        private final ValueCaster valueCaster;

        public FieldParameterWrapAdapter(Field field, ValueCaster valueCaster) {
            this.field = field;
            this.valueCaster = valueCaster;
        }


        @Override
        public Object to(Object value) {
            try {
                Object value1 = field.get(value);
                return valueCaster.to(value1);

            } catch (IllegalAccessException e) {
                throw new ZoomException(e);
            }
        }
    }

    static class FieldParameterAdapter implements ValueCaster {


        private final Field field;

        public FieldParameterAdapter(Field field) {
            this.field = field;
        }


        @Override
        public Object to(Object value) {
            try {
                return field.get(value);
            } catch (IllegalAccessException e) {
                throw new ZoomException(e);
            }
        }
    }
}
